<template>
  <div>
    <el-input
      ref="categorySelect"
      v-model="categoryName"
      placeholder="请选择主营品类"
      @focus="showCategoryDialog"
      suffix-icon="el-icon-search"
      @change="handleChange"
      :disabled="disabled"
    />
    <basic-dialog
      width="763px"
      title="选择主营品类"
      :visible="visible"
      :handle-close="closeCategoryDialog"
      :showFooter="false"
      :handleOpened="initProps"
    >
      <div v-if="!isSpecial">
        <div class="category-search">
          <el-form size="mini" ref="formData" :model="formData" inline>
            <el-form-item prop="categoryName" label="名称">
              <el-input
                placeholder="请输入品类名称"
                v-model="formData.categoryName"
                @keyup.enter.native="handleSerach"
              ></el-input>
            </el-form-item>
            <el-form-item prop="categoryName" label="编码">
              <el-input
                placeholder="请输入四级类编码"
                v-model="formData.categoryNo"
                @keyup.enter.native="handleSerach"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSerach">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-divider class="divider" content-position="left">条件查询结果：</el-divider>
        <div class="category-searchlist">
          <el-radio-group v-model="searchList.checkList" @input="handleCheckSearchList" v-loading="searchLoading">
            <el-radio
              v-for="item in searchList.dataSource"
              :label="item.categoryUuid"
              :key="item.categoryUuid"
            >
            {{ item.categoryPath }}&nbsp;&nbsp;{{ item.categoryNo }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-divider class="divider" content-position="left">品类树选择：</el-divider>
      <el-cascader-panel
        v-loading="loading"
        v-if="showPannel"
        ref="categoryPannel"
        v-model="categoryValue"
        :props="props"
        @change="handleNodeChange"
      ></el-cascader-panel>
    </basic-dialog>
  </div>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import { ApiRequest } from '@api/basePage';
import { isResponseSuccess } from '@/utils/bizUtils';

export default {
  // 选择主营品类
  name: 'MainCategorySelect',
  components: {
    BasicDialog
  },
  props: {
    value: { type: String, },
    setName: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
  },
  data () {
    return {
      searchLoading: false,
      showPannel: true,
      loading: false,
      visible: false,
      categoryName: '',
      categoryValue: '',
      props: {
        lazy: true
      },
      formData: {
        categoryName: '',
        categoryNo: '',
      },
      searchList: { // 查询列表
        dataSource: [], // 数据源
        checkList: '', // 勾选对象
      },
      apiObj: {
        // 查询一级分类
        getLevelOneCategoryList: {
          url: '/srm-admin/component/category/get-level1', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 根据父分类查询子分类
        getByParentUuid: {
          url: '/srm-admin/component/category/get-by-parent', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 按条件查询品类
        getCategoryListByKey: {
          url: '/sysback/choose/category/searchCategoryList',
          type: 'post'
        },
      },
    };
  },
  watch: {
    value: {
      handler (val) {
        if (this.setName) {
          this.categoryName = val
        }
      },
      immediate: true,
    }
  },
  computed: {
    isSpecial () {
      return sessionStorage.supplierType == 'special'
    }
  },
  created () {
    this.initProps();
  },
  methods: {
    // 初始化lazyLoad方法
    initProps () {
      this.showPannel = true;
      this.props.lazyLoad = (node, resolve) => {
        const { level, value } = node;
        if (level == 0) {
          this.loading = true;
          this.getLevelOneCategoryList().then((res) => {
            this.loading = false;
            const nodes = res.map((item) => ({
              value: item.uuid,
              label: item.categoryName,
              code: item.categoryNo,
              isMetal: item.isMetal,
              leaf: level >= 3,
              level: level + 1
            }));
            resolve(nodes);
          }).catch(() => {
            this.showPannel = false;
            this.loading = false;
            resolve(null);
          });
        } else {
          this.getLevelOtherCategoryList(value).then((res) => {
            const nodes = res.map((item) => ({
              value: item.uuid,
              label: item.categoryName,
              code: item.categoryNo,
              isMetal: item.isMetal,
              leaf: level >= 3,
              level: level + 1
            }));
            resolve(nodes);
          });
        }
      };
    },
    // 条件查询选择
    handleCheckSearchList (id) {
      const {
        categoryName,
        categoryNo,
        categoryUuid,
        isMetal
      } = this.searchList.dataSource.find(item => item.categoryUuid == id)
      this.$emit('onSelected', { categoryName, categoryNo, uuid: categoryUuid, isMetal })
      if (this.$refs['categoryPannel']) {
        this.$refs['categoryPannel'].clearCheckedNodes();
      }
      this.closeCategoryDialog()
    },
    // 表单-分类名称查询
    async handleSerach () {
      const data = {};
      const { categoryNo, categoryName } = this.formData;
      if (!categoryNo && !categoryName) {
        this.$message.warning('品类名称和品类编码不能同时为空');
        return false;
      }
      const { url, type } = this.apiObj.getCategoryListByKey;
      const param = categoryNo ? `categoryNo=${categoryNo}` : `categoryName=${categoryName}`;
      const apiUrl = `${url}?${param}`;
      this.searchLoading = true;
      const res = await ApiRequest(apiUrl, type, data, true);
      this.searchLoading = false;
      if (isResponseSuccess(res)) {
        this.searchList.checkList = '';
        this.searchList.dataSource = res.retData;
      }
    },
    // 获取一级目录
    async getLevelOneCategoryList () {
      const { result } = await ApiRequest(
        this.apiObj.getLevelOneCategoryList.url,
        this.apiObj.getLevelOneCategoryList.type,
        {},
        true
      )
      if (this.isSpecial) {
        return result.filter(item => item.categoryName == '特殊供应商')
      } else {
        return result.filter(item => item.categoryName != '特殊供应商')
      }
    },
    // 获取其它级目录
    async getLevelOtherCategoryList (categoryUuid) {
      const { result } = await ApiRequest(
        this.apiObj.getByParentUuid.url,
        this.apiObj.getByParentUuid.type,
        { parentUuid: categoryUuid },
        true
      );
      return result;
    },
    // 选择末级分类
    handleNodeChange () {
      const selectNode = this.$refs['categoryPannel'].getCheckedNodes()[0];
      if (selectNode) {
        const { code, label, value, isMetal } = selectNode.data;
        this.categoryName = label;
        this.$emit('onSelected', { categoryName: label, categoryNo: code, uuid: value, isMetal });
        this.searchList.checkList = '';
        this.closeCategoryDialog();
      }
    },
    // 清空已选分类
    clearCategoryNodes () {
      if (this.categoryName) {
        this.$refs['categoryPannel'].clearCheckedNodes();
      }
      this.$refs.formData.resetFields();
      this.searchList = {
        dataSource: [],
        checkList: ''
      }
    },
    // 展示弹框
    showCategoryDialog () {
      this.visible = true;
    },
    // 关闭弹框
    closeCategoryDialog () {
      this.visible = false;
    },
    handleChange (val) {
      // 值回显父组件
      this.$emit('input', val);
      // change事件
      this.$emit('change', val);
      this.$refs['categoryPannel'].clearCheckedNodes();
    },
  }
};
</script>
<style lang="less" scoped>
  /deep/.el-scrollbar__wrap {
    overflow-x: hidden;
    height: 100%;
  }
  .divider {
    margin: 10px 0;
  }
  .category-searchlist {
    .el-radio-group {
      border: 1px solid #ebeef5;
      padding-left: 5px;
      height: 200px;
      width: 100%;
      max-height: 200px;
      overflow-y: auto;
      label {
        display: block;
        line-height: 24px;
        &:first-child {
          margin-top: 10px;
        }
        &:last-child {
          margin-bottom: 10px;
        }
      }
    }
  }
</style>
